package dparish.client.activity;

import java.util.List;

import javax.inject.Inject;

import com.google.gwt.activity.shared.AbstractActivity;
import com.google.gwt.place.shared.PlaceController;
import com.google.gwt.user.client.ui.AcceptsOneWidget;
import com.google.inject.Provider;
import com.google.web.bindery.event.shared.EventBus;
import com.google.web.bindery.requestfactory.shared.Receiver;
import com.google.web.bindery.requestfactory.shared.ServerFailure;

import dparish.client.places.StudentAddEditPlace;
import dparish.client.proxy.StudentProxy;
import dparish.client.rf.StudentRequest;
import dparish.client.view.StudentListView;

public class StudentListActivity extends AbstractActivity implements StudentListView.Presenter<StudentProxy> {

	private List<StudentProxy> students;
	private StudentListView view;
	private PlaceController placeController;
	private Provider<StudentRequest> studentRequestProvider;
	
	@Inject
	public StudentListActivity (EventBus bus, StudentListView view, PlaceController placeController, Provider<StudentRequest> studentRequestProvider) {
		this.view = view;
		this.placeController = placeController;
		this.studentRequestProvider = studentRequestProvider;
		view.setPresenter(this);
		
	}
	@Override
	public void onSelectedEvent(StudentProxy entity) {
		StudentAddEditPlace place = new StudentAddEditPlace (entity.getId() + "");
		place.setStudent(entity);
		placeController.goTo(place);
	}

	@Override
	public void onAddEvent() {
		placeController.goTo(new StudentAddEditPlace(""));
	}

	@Override
	public void setEntities(List<StudentProxy> entities) {
		students = entities;
	}
	
	private void getStudentsFromServer() {
		studentRequestProvider.get().findAll().fire(new Receiver<List<StudentProxy>>() {

			@Override
			public void onSuccess(List<StudentProxy> response) {
				students = response;
				view.render();

			}
			
			@Override
			public void onFailure (ServerFailure error) {
				view.loadCallback(error.getMessage());
			}
			
		});
	}

	@Override
	public List<StudentProxy> getEntities() {
		return students;
	}
	@Override
	public void start(AcceptsOneWidget panel,
			com.google.gwt.event.shared.EventBus eventBus) {
		if (students == null) {
			getStudentsFromServer();
		}
		panel.setWidget(view.asWidget());
	}

}
